<template>
  <RoleModal
      :visible="isModalVisible"
      :roleId="currentRoleId"
      :roleName="currentRoleName"
      :role-data="currentRoleData"
      @visible2="getVisible"
  />
  <div class="role-list">

    <el-card class="box-card">
      <h3>角色列表</h3>
      <div class="header">
        <el-button @click="openDialog" type="primary" icon="Plus">新增角色</el-button>
        <AddRoleDialog ref="dialogRef" @success="handleSave"/>


      </div>
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column prop="roleName" label="角色名称" width="120" />
        <el-table-column prop="roleDesc" label="职责描述" />
        <el-table-column prop="count" label="人员数量" width="140">
          <template #default="scope">
            <div class="user-count-wrapper">
              <span class="user-count-number">{{ scope.row.count }}</span>

              <el-link type="primary" class="user-count-link" @click="showModal(scope.row.id,scope.row.roleName)">查看</el-link>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="添加时间" width="180" />
        <el-table-column label="启用/停用" width="120">
          <template #default="scope">
            <el-switch
                v-model="scope.row.roleStatus"
                :active-value="1"
                :inactive-value="0"
                @change="handleStatusChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button type="primary" link size="small" @click="toPermission(scope.row.roleName,scope.row.id)">权限</el-button>
            <el-button @click="editRole(scope.row)" type="primary" link size="small">编辑</el-button>
            <el-button @click="deleteRole(scope.row)" type="danger" link size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import {onMounted, ref} from 'vue';
import axios from "axios";
import {ElMessage, ElMessageBox} from "element-plus";
import AddRoleDialog from "@/views/Ye/AddRoleDialog.vue";

// ====================================================================
import RoleModal from "@/views/Ye/RoleModal.vue";
import {router} from "@/router/index.js";
//查看角色人员
const isModalVisible = ref(false);
const currentRoleId = ref(null);
const currentRoleName = ref(null);

const currentRoleData = ref([]);
const showModal = (roleId,roleName) => {
  console.log(roleId)
  currentRoleId.value = roleId;
  currentRoleName.value = roleName;
  isModalVisible.value = true;
};

const getVisible = (val) => {
  isModalVisible.value = val;
}
// ====================================================================





const tableData = ref([]);

//搜索数据库的全部的角色
const getAllRoles = () => {
  axios.get("/role/getAllRoles").then(resp => {
    tableData.value = resp.data;
  })
}
//改变角色状态
// 当 switch 状态改变时调用，用于更新后端状态
const handleStatusChange = (row) => {
  axios.post("/role/updateStatus", {
    id: row.id,
    roleStatus: row.roleStatus
  }).then(() => {
    row.roleStatus?ElMessage.success("角色启用成功！"):ElMessage.success("角色禁用成功！");
  }).catch(() => {
    ElMessage.error("状态修改失败！");
  });
};

//新增一个角色
const addRole = () => {

}
//点击保存后刷新页面
const handleSave = () => {
  getAllRoles();
}

onMounted( () => {
  //页面加载时获取所有的角色列表
  getAllRoles();
})
// ================================新增角色弹窗开始
const dialogRef = ref()

// 新增角色
const openDialog = () => {
  dialogRef.value.open('add')
}
// ================================新增角色弹窗结束
// ================================编辑角色弹窗开始
// 编辑角色
const editRole = (row) => {
  dialogRef.value.open('edit', row)
}
// ================================编辑角色弹窗结束
// ================================删除角色开始
// 删除角色
const deleteRole = (row) => {
  ElMessageBox.confirm(
      `确定要删除角色「${row.roleName}」吗？`,
      '删除确认',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        // 发起删除请求
        axios.delete(`/role/deleteRole/${row.id}`).then(resp => {
          if (resp.data) {
            ElMessage.success("删除成功");
            getAllRoles(); // 重新刷新列表
          } else {
            ElMessage.error("删除失败");
          }
        }).catch(() => {
          ElMessage.error("删除请求异常");
        });
      })
      .catch(() => {
        ElMessage.info("已取消删除");
      });
};
// ================================删除角色结束

//权限相关开始
//查看角色权限
const toPermission = (roleName,id) => {
  router.push({
    name: 'RolePermission',
    query: {
      roleName: roleName,
      id: id
    }
  });
}
//管理权限



</script>

<style scoped>
.role-list {
  padding: 20px;
  background-color: #f5f7fa;
}

.header {
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-start;
}

.el-card {
  border-radius: 8px;
}
.user-count-cell {
  display: flex;
  align-items: center;
  justify-content: flex-start;
}

.user-count-number {
  margin-right: 16px; /* 控制数字和“查看”之间的距离 */
}

.user-count-link {
  white-space: nowrap; /* 防止“查看”换行 */
}

.user-count-wrapper {
  display: flex;
  align-items: center;      /* 垂直居中 */
  justify-content: center;  /* 水平居中 */
  gap: 16px;                /* 控制数字与“查看”之间的间距 */
}

.user-count-number,
.user-count-link {
  white-space: nowrap;      /* 避免换行 */
}
</style>
